import $api from "@/api/index";
import { useCallback, useEffect, useState } from "react";
import { UserI } from "@/models/user";
import { APIPagination } from "@/models/common";

export async function getUsers(
  params?: URLSearchParams | null
): Promise<APIPagination<UserI>> {
  const res = await $api.get("api/user/", {
    params,
  });

  return res.data;
}

export async function getUser(id: string): Promise<UserI> {
  const res = await $api.get(`api/user/${id}`);

  return res.data;
}

export function useUsers(
  params?: URLSearchParams | null
): [APIPagination<UserI> | undefined, UserI[] | undefined, boolean] {
  const [isLoading, setLoading] = useState(false);
  const [data, setData] = useState<APIPagination<UserI>>();

  const load = useCallback(async () => {
    // if (!params) return;
    setLoading(true);

    try {
      const r = await getUsers(params);
      setData(r);
    } catch (error) {
      console.log({ error });
    } finally {
      setLoading(false);
    }
  }, [params]);

  useEffect(() => {
    load();
  }, [load]);

  return [data, data?.results, isLoading];
}

export async function createUser(user: Partial<UserI>): Promise<UserI> {
  const res = await $api.post(`api/user/`, user);

  return res.data;
}

export async function patchUser(user: Partial<UserI>): Promise<UserI> {
  const res = await $api.patch(`api/user/${user.id}/`, user);

  return res.data;
}

export async function getUserMe(): Promise<UserI> {
  const res = await $api.get(`api/user/me/`);

  return res?.data;
}
